package com.tianji.learning.service.impl;

import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.UserIdFunction;
import com.tianji.learning.service.UserQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserQueryServiceImpl implements UserQueryService {

    @Autowired
    private UserClient userClient;

    public Map<Long, UserDTO> queryUserMap(List<? extends UserIdFunction> questions){
        List<Long> userIds = questions.stream().map(UserIdFunction::getUserId).distinct().collect(Collectors.toList());
        List<UserDTO> users = userClient.queryUserByIds(userIds);
        if(CollUtils.isEmpty(users)){
            log.info("查询不到用户信息：{}", userIds);
            throw new BizIllegalException("网络异常");
        }
        Map<Long, UserDTO> userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        return CollUtils.isEmpty(userMap)?new HashMap<>():userMap;
    }
}
